﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;

namespace LeagueUtils
{
    /*
     * This class handles the safe repair and recovery of the League of Legends directory
     */
    public static class FileRepair
    {
        /*
         * Goes through each folder in the league directory and finds files tagged with _LT_Bak
         * which indicate that the file in that folder is a modified version. It then replaces the 
         * file with the backup (_LT_Bak version)
         */
        public static void RepairFilesRecursive(string b)
        {
            List<string> result = new List<string>();
            Stack<string> stack = new Stack<string>();
            stack.Push(b);
            while (stack.Count > 0)
            {
                string dir = stack.Pop();
                try
                {
                    result.AddRange(Directory.GetFiles(dir, "*.*"));
                    foreach (string dn in Directory.GetDirectories(dir))
                    {
                        stack.Push(dn);
                    }
                }
                catch{}
            }
            foreach (string fileName in result)
            {
                if (fileName.Contains("_LT_Bak"))
                {
                    File.Delete(fileName.Replace("_LT_Bak",""));
                    File.Move(fileName, fileName.Replace("_LT_Bak", ""));
                }
            }
            //return result;
        }

        /*
         * This creates a backup of the given file (if it exists) by copying the file to the same path
         * with _LT_Bak tagged on the end of it.
         */
        public static void BackupFile(string filePath)
        {
            if (!File.Exists(filePath.Insert(filePath.LastIndexOf("."), "_LT_Bak")))
                File.Copy(filePath, filePath.Insert(filePath.LastIndexOf("."), "_LT_Bak"));
        }
    }
}

